<template>
  <div class="login-container">
    <el-card class="login-card">
      <template #header>
        <div class="login-header">
          <h2>系统登录</h2>
        </div>
      </template>
      <el-form
        ref="loginFormRef"
        :model="loginForm"
        :rules="loginRules"
        label-width="80px"
        class="login-form"
      >
        <el-form-item label="用户名" prop="username">
          <el-input
            v-model="loginForm.username"
            placeholder="请输入用户名"
            prefix-icon="el-icon-user"
            clearable
          />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input
            v-model="loginForm.password"
            type="password"
            placeholder="请输入密码"
            prefix-icon="el-icon-lock"
            show-password
            clearable
            @keyup.enter="handleLogin"
          />
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            :loading="loading"
            class="login-button"
            @click="handleLogin"
          >
            登录
          </el-button>
          <div class="register-link">
            <el-button type="text" @click="goToRegister">没有账号？去注册</el-button>
          </div>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import { ref, reactive } from 'vue';
import { useStore } from 'vuex';
import { useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';

export default {
  name: 'LoginPage',
  setup() {
    const store = useStore();
    const router = useRouter();
    const loginFormRef = ref(null);
    const loading = ref(false);

    const loginForm = reactive({
      username: '',
      password: ''
    });

    const loginRules = {
      username: [
        { required: true, message: '请输入用户名', trigger: 'blur' },
        { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
      ],
      password: [
        { required: true, message: '请输入密码', trigger: 'blur' },
        { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
      ]
    };

    const handleLogin = () => {
      loginFormRef.value.validate(valid => {
        if (valid) {
          loading.value = true;
          store
            .dispatch('login', loginForm)
            .then(() => {
              ElMessage.success('登录成功');
              
              // 检查是否为admin用户，如果是则强制添加权限
              if (loginForm.username === 'admin') {
                console.log('[Login] 检测到admin用户登录，强制设置权限...');
                
                // 直接添加权限到userInfo
                const userInfoStr = localStorage.getItem('userInfo');
                if (userInfoStr) {
                  try {
                    const userInfo = JSON.parse(userInfoStr);
                    
                    // 确保permissions是数组
                    if (!userInfo.permissions || !Array.isArray(userInfo.permissions)) {
                      userInfo.permissions = [];
                    }
                    
                    // 添加所需权限
                    const requiredPermissions = [
                      'graph:view',
                      'analysis:supply-chain',
                      'analysis:industry-chain',
                      'analysis:company-risk',
                      'analysis:centrality',
                      'analysis:community',
                      'analysis:pathfinding'
                    ];
                    
                    // 添加缺失的权限
                    let added = 0;
                    for (const perm of requiredPermissions) {
                      if (!userInfo.permissions.includes(perm)) {
                        userInfo.permissions.push(perm);
                        added++;
                      }
                    }
                    
                    console.log(`[Login] 已添加${added}个权限，更新后的权限列表:`, userInfo.permissions);
                    
                    // 保存回localStorage
                    localStorage.setItem('userInfo', JSON.stringify(userInfo));
                    
                    // 更新store中的权限
                    store.commit('SET_PERMISSIONS', userInfo.permissions);
                    
                    // 刷新用户信息，确保权限生效
                    store.dispatch('getUserInfo', true)
                      .then(() => {
                        console.log('[Login] 用户信息刷新成功，即将跳转首页');
                        router.push({ path: '/' });
                      })
                      .catch(error => {
                        console.error('[Login] 刷新用户信息失败:', error);
                        // 即使失败也跳转
                        router.push({ path: '/' });
                      });
                  } catch (e) {
                    console.error('[Login] 处理权限时出错:', e);
                    router.push({ path: '/' });
                  }
                } else {
                  console.error('[Login] 未找到用户信息');
                  router.push({ path: '/' });
                }
              } else {
                // 非admin用户直接跳转
                router.push({ path: '/' });
              }
            })
            .catch(error => {
              console.error('登录失败:', error);
              ElMessage.error(error.message || '登录失败，请重试');
            })
            .finally(() => {
              loading.value = false;
            });
        } else {
          return false;
        }
      });
    };

    const goToRegister = () => {
      router.push('/register');
    };

    return {
      loginFormRef,
      loginForm,
      loginRules,
      loading,
      handleLogin,
      goToRegister
    };
  }
};
</script>

<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  background-image: url('../assets/login_background.jpeg');
  background-size: cover;
  background-position: center;
  background-repeat: no-repeat;
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  width: 100%;
}

.login-card {
  width: 400px;
  border-radius: 8px;
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.3);
  background-color: rgba(255, 255, 255, 0.9);
  backdrop-filter: blur(5px);
  transform: translateY(-5%);
}

.login-header {
  text-align: center;
  padding: 10px 0;
}

.login-header h2 {
  margin: 0;
  font-size: 24px;
  color: #303133;
  font-weight: 600;
}

.login-form {
  padding: 20px 20px;
}

.login-button {
  width: 100%;
  margin-bottom: 15px;
  height: 40px;
  font-size: 16px;
}

.register-link {
  text-align: center;
  margin-top: 10px;
}

@media (max-width: 480px) {
  .login-card {
    width: 90%;
    max-width: 400px;
  }
}
</style> 